package connector

import (
	"common/logs"
	"fmt"
	"framework/game"
	"framework/net"
	"framework/remote"
)

type Connector struct { //Con控制器
	isRunning bool //判断有没有启动
	wsManager *net.Manager
	handlers  net.LogicHandler
	remoteCli remote.Client
}

func Default() *Connector {
	return &Connector{
		wsManager: net.NewManager(),
		handlers:  make(net.LogicHandler),
	}
}

func (c *Connector) Run(serverId string) error {
	if !c.isRunning {
		logs.Info("-------" + serverId)
		c.wsManager = net.NewManager()
		c.wsManager.ConnectorHandlers = c.handlers
		//启动nat nats server不会存储消息
		c.remoteCli = remote.NewNatsClient(serverId, c.wsManager.RemoteReadChan)
		c.remoteCli.Run()
		c.wsManager.RemoteCli = c.remoteCli

		//http ws run
		c.Serve(serverId)
	}
	return nil
}

func (c *Connector) Serve(serverId string) {
	logs.Info("run connector:%v", serverId)
	connectorConfig := game.Conf.GetConnector(serverId)
	if connectorConfig == nil {
		logs.Fatal("no connector config found")
	}
	c.isRunning = true
	c.wsManager.ServerId = serverId
	addr := fmt.Sprintf("%s:%d", connectorConfig.Host, connectorConfig.ClientPort)
	c.isRunning = true
	c.wsManager.Run(addr) //启动websocket的地址和端口号
}

func (c *Connector) Close() {
	if c.wsManager != nil {
		c.wsManager.Close()
	}
}

func (c *Connector) RegisterHandler(handlers net.LogicHandler) {
	c.handlers = handlers
}
